// src/utils/initialization.ts
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Dimensions, Platform } from 'react-native';
import NetInfo from '@react-native-community/netinfo';
import DeviceInfo from 'react-native-device-info';
import SplashScreen from 'react-native-splash-screen';
import { store } from '../store/store';
import {
  setCredentials,
  loadUserInfo, initializeAuth
} from '../store/slices/authSlice';
import {
  loadSettingsFromStorage,
  setLanguage
} from '../store/slices/settingsSlice';
import {
  loadSubscriptionStatus
} from '../store/slices/subscriptionSlice';
import {
  setNetworkState,
  setScreenDimensions,
  setOrientation
} from '../store/slices/uiSlice';
import billingService from '../services/billingService';
import notificationService from '../services/notificationService';
import websocketService from '../services/websocketService';
import analyticsService from '../services/analyticsService';
import cacheService from '../services/cacheService';
import { setupErrorHandling } from './errorHandling';
import { checkForUpdates } from './appUpdates';
import { loadFonts } from './fonts';
import { configureLocalization } from './localization';

interface InitializationOptions {
  skipAuth?: boolean;
  skipBilling?: boolean;
  skipNotifications?: boolean;
  skipWebSocket?: boolean;
  skipAnalytics?: boolean;
}

export async function initializeApp(options: InitializationOptions = {}) {
  try {
    console.log('[App] Starting initialization...');

    // 1. 设置错误处理
    setupErrorHandling();

    // 2. 加载字体
    await loadFonts();

    // 3. 配置本地化
    await configureLocalization();

    // 4. 清理过期缓存
    await cacheService.clearExpired();

    // 5. 加载本地设置
    await loadSettings();

    // 6. 检查网络状态
    await checkNetworkStatus();

    // 7. 设置设备信息
    await setupDeviceInfo();

    // 8. 初始化认证
    if (!options.skipAuth) {
      initializeAuth();
    }

    // 9. 初始化订阅服务
    if (!options.skipBilling) {
      await initializeBilling();
    }

    // 10. 初始化通知服务
    if (!options.skipNotifications) {
      await initializeNotifications();
    }

    // 11. 初始化WebSocket
    if (!options.skipWebSocket) {
      await initializeWebSocket();
    }

    // 12. 初始化分析服务
    if (!options.skipAnalytics) {
      await initializeAnalytics();
    }

    // 13. 检查应用更新
    await checkForUpdates();

    // 14. 预加载数据
    await preloadData();

    // 15. 隐藏启动屏
    SplashScreen.hide();

    console.log('[App] Initialization completed');

    return true;
  } catch (error) {
    console.error('[App] Initialization failed:', error);

    // 记录错误
    analyticsService.trackError(error as Error, true);

    // 隐藏启动屏
    SplashScreen.hide();

    return false;
  }
}

// 加载本地设置
async function loadSettings() {
  try {
    const settingsJson = await AsyncStorage.getItem('settings');
    if (settingsJson) {
      const settings = JSON.parse(settingsJson);
      store.dispatch(loadSettingsFromStorage(settings));
    }

    // 加载语言设置
    const language = await AsyncStorage.getItem('language');
    if (language) {
      store.dispatch(setLanguage(language));
    }
  } catch (error) {
    console.error('[Settings] Load error:', error);
  }
}

// 检查网络状态
async function checkNetworkStatus() {
  const netInfoState = await NetInfo.fetch();

  store.dispatch(setNetworkState({
    isOnline: netInfoState.isConnected || false,
    connectionType: netInfoState.type,
  }));

  // 监听网络状态变化
  NetInfo.addEventListener((state) => {
    store.dispatch(setNetworkState({
      isOnline: state.isConnected || false,
      connectionType: state.type,
    }));
  });
}

// 设置设备信息
async function setupDeviceInfo() {
  try {
    const deviceId = await DeviceInfo.getUniqueId();
    const deviceName = await DeviceInfo.getDeviceName();
    const systemVersion = DeviceInfo.getSystemVersion();
    const appVersion = DeviceInfo.getVersion();
    const buildNumber = DeviceInfo.getBuildNumber();

    // 保存设备信息
    await AsyncStorage.setItem('deviceInfo', JSON.stringify({
      deviceId,
      deviceName,
      platform: Platform.OS,
      systemVersion,
      appVersion,
      buildNumber,
    }));

    // 设置屏幕尺寸
    const { width, height } = Dimensions.get('window');
    store.dispatch(setScreenDimensions({ width, height }));

    // 监听屏幕方向变化
    Dimensions.addEventListener('change', ({ window }) => {
      store.dispatch(setScreenDimensions({
        width: window.width,
        height: window.height,
      }));

      const orientation = window.width > window.height ? 'landscape' : 'portrait';
      store.dispatch(setOrientation(orientation));
    });
  } catch (error) {
    console.error('[Device] Setup error:', error);
  }
}

// 初始化认证
// async function initializeAuth() {
//   try {
//     const token = await AsyncStorage.getItem('token');
//     const refreshToken = await AsyncStorage.getItem('refreshToken');
//     const userJson = await AsyncStorage.getItem('user');
//
//     if (token && userJson) {
//       const user = JSON.parse(userJson);
//
//       // 设置认证信息
//       store.dispatch(setCredentials({
//         user,
//         token,
//         refreshToken: refreshToken || undefined,
//       }));
//
//       // 加载最新用户信息
//       store.dispatch(loadUserInfo());
//     }
//   } catch (error) {
//     console.error('[Auth] Initialization error:', error);
//
//     // 清除可能损坏的认证数据
//     await AsyncStorage.multiRemove(['token', 'refreshToken', 'user']);
//   }
// }

// 初始化订阅服务
async function initializeBilling() {
  try {
    await billingService.initialize();

    // 加载订阅状态
    const { isAuthenticated } = store.getState().auth;
    if (isAuthenticated) {
      store.dispatch(loadSubscriptionStatus());
    }
  } catch (error) {
    console.error('[Billing] Initialization error:', error);
  }
}

// 初始化通知服务
async function initializeNotifications() {
  try {
    notificationService.initialize();

    // 请求通知权限
    const hasPermission = await notificationService.requestPermissions();
    console.log('[Notifications] Permission:', hasPermission);
  } catch (error) {
    console.error('[Notifications] Initialization error:', error);
  }
}

// 初始化WebSocket
async function initializeWebSocket() {
  try {
    const { isAuthenticated } = store.getState().auth;

    if (isAuthenticated) {
      await websocketService.connect({
        reconnect: true,
        reconnectInterval: 5000,
        maxReconnectAttempts: 5,
      });

      // 设置WebSocket消息处理
      setupWebSocketHandlers();
    }
  } catch (error) {
    console.error('[WebSocket] Initialization error:', error);
  }
}

// 设置WebSocket消息处理器
function setupWebSocketHandlers() {
  // 聊天消息
  websocketService.on('chat', (data) => {
    console.log('[WebSocket] Chat message:', data);
    // 处理聊天消息
  });

  // 通知消息
  websocketService.on('notification', (data) => {
    console.log('[WebSocket] Notification:', data);
    // 显示通知
    notificationService.showLocalNotification({
      title: data.title,
      message: data.message,
      data: data.data,
    });
  });

  // 订阅更新
  websocketService.on('subscription', (data) => {
    console.log('[WebSocket] Subscription update:', data);
    // 更新订阅状态
    store.dispatch(loadSubscriptionStatus());
  });
}

// 初始化分析服务
async function initializeAnalytics() {
  try {
    const { user } = store.getState().auth;

    if (user) {
      await analyticsService.setUserProperties({
        userId: user.id.toString(),
        email: user.email,
        subscription: store.getState().subscription.subscription?.plan,
      });
    }

    // 记录应用启动
    analyticsService.track('app_start', {
      platform: Platform.OS,
      version: DeviceInfo.getVersion(),
    });
  } catch (error) {
    console.error('[Analytics] Initialization error:', error);
  }
}

// 预加载数据
async function preloadData() {
  try {
    const { isAuthenticated } = store.getState().auth;

    if (!isAuthenticated) return;

    // 并行加载数据
    await Promise.all([
      // 加载聊天历史
      loadChatHistory(),
      // 加载翻译历史
      loadTranslationHistory(),
      // 加载语音记录
      loadVoiceHistory(),
      // 加载使用统计
      loadUsageStats(),
    ]);
  } catch (error) {
    console.error('[Preload] Error:', error);
  }
}

async function loadChatHistory() {
  // 从缓存加载聊天历史
  const cached = await cacheService.get('chat_history');
  if (cached) {
    // 更新store
  }
}

async function loadTranslationHistory() {
  // 从缓存加载翻译历史
  const cached = await cacheService.get('translation_history');
  if (cached) {
    // 更新store
  }
}

async function loadVoiceHistory() {
  // 从缓存加载语音记录
  const cached = await cacheService.get('voice_history');
  if (cached) {
    // 更新store
  }
}

async function loadUsageStats() {
  // 从缓存加载使用统计
  const cached = await cacheService.get('usage_stats');
  if (cached) {
    // 更新store
  }
}